package com.tianji.promotion.service.impl;

import com.tianji.promotion.constants.PromotionConstants;
import com.tianji.promotion.domain.po.Coupon;
import com.tianji.promotion.domain.po.ExchangeCode;
import com.tianji.promotion.mapper.ExchangeCodeMapper;
import com.tianji.promotion.service.IExchangeCodeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.promotion.utils.CodeUtil;
import org.checkerframework.checker.units.qual.A;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import static com.tianji.promotion.constants.PromotionConstants.COUPON_CODE_SERIAL_KEY;

/**
 * <p>
 * 兑换码 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-03-29
 */
@Service
public class ExchangeCodeServiceImpl extends ServiceImpl<ExchangeCodeMapper, ExchangeCode> implements IExchangeCodeService {

    private BoundValueOperations<String, String> ops;

    public ExchangeCodeServiceImpl(StringRedisTemplate redisTemplate) {
        this.ops = redisTemplate.boundValueOps(COUPON_CODE_SERIAL_KEY);
    }
    /**
     * 兑换码服务的异步生成兑换码
     *
     * @param coupon
     */
    @Async("exchangeCodeExecutor")
    @Override
    @Transactional
    public void asyncGenerateCode(Coupon coupon) {
        // 发放数量
        Integer totalNum = coupon.getTotalNum();

        // 1、获取Redis自增序列号
        Long cur1 = ops.increment(totalNum);
        if (cur1 == null) {
            return;
        }
        Integer cur = cur1.intValue();

        List<ExchangeCode> list = new ArrayList<>(totalNum);
        for (int i = cur - totalNum + 1; i <= cur; i++) {
            // 2、生成兑换码
            ExchangeCode exchangeCode = new ExchangeCode();
            exchangeCode.setCode(CodeUtil.generateCode(i, coupon.getId()));
            exchangeCode.setId(i);
            exchangeCode.setExchangeTargetId(coupon.getId());
            exchangeCode.setExpiredTime(coupon.getIssueEndTime());
            list.add(exchangeCode);
        }
        // 3、保存到数据库
        this.saveBatch(list);
    }
}
